package com.sinopec.handdevice.view;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.jakewharton.rxbinding3.view.RxView;
import com.orhanobut.hawk.Hawk;
import com.sinopec.basemodule.AppConstants;
import com.sinopec.basemodule.base.BaseActivity;
import com.sinopec.basemodule.base.CustomToolbar;
import com.sinopec.basemodule.model.app_model.WelcomeModel;
import com.sinopec.basemodule.utils.ShowImageUtils;
import com.sinopec.basemodule.widget.CustomCircleProgressBar;
import com.sinopec.handdevice.R;
import com.sinopec.handdevice.contract.WelcomeContract;
import com.sinopec.handdevice.presenter.WelcomePresenter;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author lwj
 * @ClassName: WelcomeActivity
 * @Description: 启动页
 * @date 2019/3/6 10:50
 */
public class WelcomeActivity extends BaseActivity<WelcomePresenter> implements WelcomeContract.View {
    private static final String TAG = WelcomeActivity.class.getName();
    //广告图
    private ImageView iv_welcome;
    private CustomCircleProgressBar circleProgressBar;
    //跳过布局包裹
    private FrameLayout fl_skip;
    //app启动图展示时长（秒）
    private int duration = 3;
    //app启动图跳转链接
    private String figureSkipLinks;
    //app启动图
    private String starTheFigure;
    //倒计时文本
    private TextView time_count;
    private Disposable disposable;

    @Override
    protected void initView(Bundle savedInstanceState) {
        //广告图
        iv_welcome = findViewById(R.id.iv_welcome);
        //倒计时文本
        time_count = findViewById(R.id.time_count);
        //圆形进度条
        circleProgressBar = findViewById(R.id.circleProgressbar);
        //跳过布局包裹
        fl_skip = findViewById(R.id.fl_skip);
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        //跳过广告页
        addDisposable(RxView.clicks(fl_skip)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object view) throws Exception {
                        WelcomeActivity.this.skipWelcome();
                        //手动停止圆形进度条
                        circleProgressBar.getAnimator().cancel();
                        //手动停止倒计时
                        if (disposable != null) {
                            disposable.dispose();
                        }
                    }
                }));
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter = new WelcomePresenter(this);
        mPresenter.requestConfig();
    }

    @Override
    public int getContentView() {
        return R.layout.activity_welcome;
    }

    @Override
    public void configToolbar(CustomToolbar rToolbar) {
        rToolbar.setToolbarVisible(false);
    }

    /**
     * 返回键不可用
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void refreshUI(WelcomeModel model) {
        if (model != null) {
            if (!TextUtils.isEmpty(model.getFigureShowTime())) {
                duration = Integer.parseInt(model.getFigureShowTime());
            }
            starTheFigure = model.getStarTheFigure();
            //图片链接不为0展示倒计时
            if (!TextUtils.isEmpty(starTheFigure)) {
                String url = model.getStarTheFigure();
                ShowImageUtils.showImageView(getContext(), R.drawable.welcome_bg, url, iv_welcome);
                fl_skip.setVisibility(View.VISIBLE);
                circleProgressBar.setProgress(100, duration * 1000);
                Observable.interval(0, 1, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .take(duration + 1)
                        .map(aLong -> duration - aLong).subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (aLong == 0) {
                            time_count.setText("1");
                        } else {
                            time_count.setText(aLong + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        //跳过广告页
                        skipWelcome();
                    }
                });
            } else {
                //跳过广告页
                skipWelcome();
            }

        }
    }

    /**
     * @author lwj
     * @Description: 广告页请求失败
     * @date 2019/3/6 15:49
     */
    @Override
    public void requestFail() {
        //跳过广告页
        skipWelcome();
    }

    /**
     * @author lwj
     * @Description:跳过广告页
     * @date 2019/3/6 16:10
     */
    private void skipWelcome() {
        boolean isFirstIn = Hawk.get(AppConstants.IS_FIRST_IN, true);
        if (isFirstIn) {
            Hawk.put(AppConstants.IS_FIRST_IN, false);
            navigationTo(GuideActivity.class);
            getContext().finish();
        } else {
            mPresenter.gotoLoginOrMain();
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        if (disposable != null) {
            disposable.dispose();
        }
        super.onDestroy();
    }
}
